import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入组件
import Login from '@/views/login/index.vue'
import Layout from '@/views/layout/index.vue'
import NotFound from '@/views/404/index.vue'
// 导入二级路由
import Home from '@/views/layout/home'
import QA from '@/views/layout/question'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'
import store from '@/store'
Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    component: Layout,
    // 重定向
    redirect: '/home',
    children: [
      {
        // path写为空，会有一个问题，导航不高亮
        // path: '',
        path: 'home',
        component: Home
      },
      {
        path: '/qa',
        component: QA
      },
      {
        path: '/video',
        component: Video
      },
      {
        path: '/user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})
const loginURL = ['/user']
// 创建全局的导航守卫
router.beforeEach(function (to, from, next) {
  // console.log(from)
  // console.log(to)
  // next()
  // 1.判断是否有token
  const token = store.state.user.token.token
  if (token) {
    next()
  } else {
    // 没有token
    if (loginURL.some((item) => to.path === item)) {
      // if成立，需要登录
      next('/login')
    } else {
      next()
    }
  }
})
export default router
